/* ID选择函数*/
function $(id){
  return document.getElementById(id);
}

/* 跨浏览器事件绑定 */
function on(el, type, fn){
  if(el.addEventListener){
    el.addEventListener(type, fn, false);
  }else if(el.attachEvent){
    el.attachEvent('on' + type, fn);
  }else{
    el['on' + type] = fn;
  }
}
/* 保存DOM节点 */
var formGraTime = $('form-gra-time'),
    citySelect = $('city-select'),
    aqiChartWrap = document.getElementsByClassName('aqi-chart-wrap')[0];
/* 数据格式演示
var aqiSourceData = {
  "北京": {
    "2016-01-01": 10,
    "2016-01-02": 10,
    "2016-01-03": 10,
    "2016-01-04": 10
  }
};
*/

// 以下两个函数用于随机模拟生成测试数据
function getDateStr(dat) {
  var y = dat.getFullYear();
  var m = dat.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = dat.getDate();
  d = d < 10 ? '0' + d : d;
  return y + '-' + m + '-' + d;
}
function randomBuildData(seed) {
  var returnData = {};
  var dat = new Date("2016-01-01");
  var datStr = ''
  for (var i = 1; i < 92; i++) {
    datStr = getDateStr(dat);
    returnData[datStr] = Math.ceil(Math.random() * seed);
    dat.setDate(dat.getDate() + 1);
  }
  return returnData;
}

var aqiSourceData = {
  "北京": randomBuildData(500),
  "上海": randomBuildData(300),
  "广州": randomBuildData(200),
  "深圳": randomBuildData(100),
  "成都": randomBuildData(300),
  "西安": randomBuildData(500),
  "福州": randomBuildData(100),
  "厦门": randomBuildData(100),
  "沈阳": randomBuildData(500)
};

// 用于渲染图表的数据
var chartData = {};

// 记录当前页面的表单选项
var pageState = {
  nowSelectCity:'北京',
  nowGraTime: "day"
}

/**
 * 渲染图表
 */
function renderChart() {
  var temp = '', color = '';

  for(var i in chartData){
    color = (~~(Math.random()*(1<<24)));
    if(color < 0x100000) color += 0x100000;
    temp += '<div style="height:' + chartData[i] + 'px;background:#' + color.toString(16) + '" title="' + i + ':' + chartData[i] + '"></div>';
  }
  aqiChartWrap.innerHTML = temp;
}

/**
 * 日、周、月的radio事件点击时的处理函数
 */
function graTimeChange() {
  // 确定是否选项发生了变化 
  if(this.value === pageState.nowGraTime){
    return;
  }
  // 设置对应数据
  pageState.nowGraTime = this.value;
  // 调用图表渲染函数
  initAqiChartData();
}

/**
 * select发生变化时的处理函数
 */
function citySelectChange() {
  // 确定是否选项发生了变化 
  if(this.value === pageState.nowSelectCity){
    return;
  }
  // 设置对应数据
  pageState.nowSelectCity = this.value;
  // 调用图表渲染函数
  initAqiChartData();
}

/**
 * 初始化日、周、月的radio事件，当点击时，调用函数graTimeChange
 */
function initGraTimeForm() {
  var input = formGraTime.getElementsByTagName('input');
  for(var i in input){
    on(input[i],'click',graTimeChange);
  }
}

/**
 * 初始化城市Select下拉选择框中的选项
 */
function initCitySelector() {
  // 读取aqiSourceData中的城市，然后设置id为city-select的下拉列表中的选项
  var temp = '';
  for(var i in aqiSourceData){
    temp += '<option value="' + i + '">' + i + '</option>';
  }
  citySelect.innerHTML = temp;
  // 给select设置事件，当选项发生变化时调用函数citySelectChange
  on(citySelect, 'change', citySelectChange);
}

/**
 * 初始化图表需要的数据格式
 */
function initAqiChartData() {
  // 将原始的源数据处理成图表需要的数据格式
  // 处理好的数据存到 chartData 中
  chartData = {};
  var temp = 0, count = 0;
  var source = aqiSourceData[pageState.nowSelectCity];
  var city = pageState.nowSelectCity;
  if(pageState.nowGraTime === 'week'){
    
    for(var j = 0; j < Math.ceil(Object.keys(source).length/7); j++){
      chartData['第' + (j+1) + '周'] = 0;
      Object.keys(source).forEach(function(item, index){
        if(Math.floor(index/7) === j){
          chartData['第' + (j+1) + '周'] = chartData['第' + (j+1) + '周'] + source[item];
        }
      });
      chartData['第' + (j+1) + '周'] = Math.round(chartData['第' + (j+1) + '周'] / 7);
    }
    
  }else if (pageState.nowGraTime === 'month'){
    for(var i = 0; i < Math.floor(Object.keys(source).length/30); i++){
      chartData['第' + (i+1) + '月'] = 0;
      count = 0;
      Object.keys(source).forEach(function(item, index){
        temp = item.split('-');
        if(+temp[1] === (i+1)){
          count++;
          chartData['第' + (i+1) + '月'] += source[item];
        }
      });
      console.log(count);
      chartData['第' + (i+1) + '月'] = Math.round(chartData['第' + (i+1) + '月'] / count);
    }
  }else if (pageState.nowGraTime === 'day'){
    for(var date in source){
      chartData[date] = source[date];
    }
  }
  // console.log(chartData);
  renderChart();
}

/**
 * 初始化函数
 */
function init() {
  initGraTimeForm()
  initCitySelector();
  initAqiChartData();
}

init();
